package com.create404.suishoupai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.create404.suishoupai.entity.ChatRecord;
import com.create404.suishoupai.mapper.ChatRecordMapper;
import com.create404.suishoupai.service.IChatRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author create404
 * @since 2021-07-17
 */
@Service
public class ChatRecordServiceImpl extends ServiceImpl<ChatRecordMapper, ChatRecord> implements IChatRecordService {

    @Autowired
    ChatRecordMapper chatRecordMapper;

    /**
     * 根据双方id查找聊天记录，并按时间排序
     *
     * @param me    自己的id
     * @param other 对方的id
     * @return
     */
    @Override
    public List<ChatRecord> queryRecords(int me, int other) {
        QueryWrapper<ChatRecord> wrapper = new QueryWrapper<>();
        wrapper.and(wq -> wq
                .eq("sender_id", me)
                .eq("receiver_id", other));
        wrapper.or(wq -> wq
                .eq("receiver_id", me)
                .eq("sender_id", other));
        wrapper.orderByDesc("time");
        return chatRecordMapper.selectList(wrapper);
    }

    /**
     * 保存一条聊天记录
     *
     * @param chatRecord
     */
    @Override
    public void add(ChatRecord chatRecord) {
        chatRecordMapper.insert(chatRecord);
    }

    /**
     * 根据自己和对方的id计算聊天记录中未读记录条数
     *
     * @param me    自己的id
     * @param other 对方的id
     * @return
     */
    @Override
    public int getUnreadNum(int me, int other) {

        QueryWrapper<ChatRecord> wrapper = new QueryWrapper<>();
        wrapper.and(wq -> wq
                .eq("receiver_id", me)
                .eq("sender_id", other));
        wrapper.eq("is_read", "0");
        return chatRecordMapper.selectCount(wrapper);

    }

    /**
     * 根据自己和对方的id将记录改为已读
     *
     * @param me    自己的id
     * @param other 对方的id
     */
    @Override
    public void updateIsread(int me, int other) {
        UpdateWrapper<ChatRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.and(wq -> wq
                .eq("receiver_id", me)
                .eq("sender_id", other)
                .eq("is_read", "0"));
        ChatRecord record = new ChatRecord();
        record.setIsRead("1");
        chatRecordMapper.update(record, updateWrapper);
    }

    @Override
    public void updateSystemIsread(int recordId) {
        UpdateWrapper<ChatRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", recordId);
        ChatRecord record = new ChatRecord();
        record.setIsRead("1");
        chatRecordMapper.update(record, updateWrapper);
    }
}
